/**
 * 
 */
package com.orange.controller.school;

import java.io.File;
import java.io.FileInputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.orange.controller.BaseController;
import com.orange.dbhelp.page.Page;
import com.orange.handler.AuthExportGroupService;
import com.orange.handler.AuthQuestionnaireService;
import com.orange.handler.AuthSchoolService;
import com.orange.handler.expert.AuthSpecialTaskService;
import com.orange.modules.bean.SessionUser;
import com.orange.modules.entity.expert.AuthQuestionnaire;
import com.orange.modules.entity.expert.AuthSchoolQuestionnaire;
import com.orange.modules.entity.expert.AuthSpecialTask;
import com.orange.modules.entity.manage.AuthOrgUser;
import com.orange.modules.entity.manage.AuthSysDownload;
import com.orange.modules.entity.school.AuthSchool;
import com.orange.util.ReturnCode;
import com.orange.util.AppConfig;
/**
 * @author gaogs
 *
 *         2016-10-16
 */
@Controller
@RequestMapping("/questionnaire")
public class AuthQuestionnaireController extends BaseController {

	private static final Logger log = Logger.getLogger(AuthQuestionnaireController.class);

	@Autowired
	private AuthQuestionnaireService authQuestionnaireService;
	@Autowired
	private AuthSpecialTaskService authSpecialTaskService;
	@Autowired
	private AuthSchoolService authSchoolService;
	@Autowired
	private AppConfig appconfig;
	@Autowired
	private AuthExportGroupService authExportGroupService;
	
	/**
	 * 新增调查问卷
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/updateAuthSchoolInfo", produces = MediaType.APPLICATION_JSON_VALUE+ ";charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> updateAuthSchoolInfo(HttpServletRequest request,@RequestBody Map<String, String> map) throws SQLException {
		try {
			String schoolId = map.get("schoolId");
			String studentFileName = map.get("studentFileName");
			String studentFileUrl = map.get("studentFileUrl");
			String teacherFileName = map.get("teacherFileName");
			String teacherFileUrl = map.get("teacherFileUrl");
			String employerFileName = map.get("employerFileName");
			String employerFileUrl = map.get("employerFileUrl");
			String overallSatisfaction = map.get("overallSatisfaction");
			/*String updateTime = map.get("updateTime");
			String createTime = map.get("createTime");	*/
			AuthQuestionnaire as = new AuthQuestionnaire();
			as.setSchoolId(schoolId);
			as.setStudentFileName(studentFileName);
			as.setStudentFileUrl(studentFileUrl);
			as.setTeacherFileName(teacherFileName);
			as.setTeacherFileUrl(teacherFileUrl);
			as.setEmployerFileName(employerFileName);
			as.setEmployerFileUrl(employerFileUrl);
			as.setOverallSatisfaction(overallSatisfaction);		
			as.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			as.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			authQuestionnaireService.updateAuthSchoolInfo(as);
			return toResponse(as, ReturnCode.SUCCESS, "新增问卷调查表成功");
		} catch (Exception e) {
			log.info("新增问卷调查表失败", e);
			return toResponse(null, ReturnCode.FAIL, "新增问卷调查表失败");
		}
	}

	/**
	 * 根据id查询机构信息
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthQuestionnaireInfoBypid", produces = MediaType.APPLICATION_JSON_VALUE+ ";charset=UTF-8", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<String> queryAuthQuestionnaireInfoBypid(HttpServletRequest request,HttpServletResponse response,
			@RequestParam String pid)throws SQLException {
		try {
			AuthSchoolQuestionnaire a = authQuestionnaireService.AuthSchoolQuestionnaire(pid);
			return toResponse(a, ReturnCode.SUCCESS, "根据id查询调查问卷表信息成功");
		} catch (Exception e) {
			log.info("根据id查询调查问卷表信息失败", e);
			return toResponse(null, ReturnCode.FAIL, "根据id查询调查问卷表信息失败");
		}
	}

	/**
	 * 分页查询所有机构列表
	 * 
	 * @param request
	 * @param map
	 * @return
	 * @throws SQLException
	 */
	@RequestMapping(value = "/queryAuthQuestionnairePage", produces = MediaType.APPLICATION_JSON_VALUE+ ";charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> queryAuthQuestionnairePage(HttpServletRequest request, @RequestBody Map<String, String> map) throws SQLException {	
		try {
			String pageNumber = map.get("pageNumber");
			String pageSize = map.get("pageSize");
			if (StringUtils.isBlank(pageNumber))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "数量不能为空!");
			if (StringUtils.isBlank(pageSize))
				return toResponse(null, ReturnCode.PARAMETER_NOT_NULL, "页数不能为空!");
			
			Page<AuthSchoolQuestionnaire> page =authQuestionnaireService.queryAuthQuestionnairePage(map);
			return toResponse(page, ReturnCode.SUCCESS, "分页查询调查问卷表成功");
		} catch (Exception e) {
			log.info("分页查询调查问卷表失败",e);
			return toResponse(null, ReturnCode.FAIL, "分页查询调查问卷表失败");
		}
	}
	
	/**
	 * 专业技能项目用表
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/uploadTaskAuthQuestionnaire" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(
			@RequestParam("file")MultipartFile filedata
			){
		try {
			String returnDatasUrl = null;
	  		String datasfile = appconfig.getFilePath();
	  		
	  		//取得可上传的文件类型  
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));
	  		
	  		String fileName = filedata.getOriginalFilename();  
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
	  		//对扩展名进行小写转换  
	  		ext = ext.toLowerCase();  
	  		/*//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
	  				(int)(Math.random()*10000) + "." + ext;*/
	  		File file = null;
	  		if(!fileTypes.contains(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024>appconfig.getFileSize()){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}
	  		
	  		Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();
            String pathbig=datasfile+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
				
		    returnDatasUrl = y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
			return toResponse(returnDatasUrl,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			log.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	   private List<String> arrayToList(String[] strs){
	    	List<String> list=new ArrayList<String>();
	    	if(strs.length>0){
	    		for(int a =0;a<strs.length;a++){
	    			list.add(strs[a].toString().trim());
	    		}
	    	}
			return list;
	    	
	    }
		/**
		 * 下载文档
		 * @param request
		 * @param response
		 * @param map
		 * @return
		 */
		@RequestMapping(value="/downloadFileQuestionnaire" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFileQuestionnaire(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid,@RequestParam int type){
			try {
				AuthQuestionnaire as = authQuestionnaireService.queryAuthQuestionnaireInfoBypid(pid);
				if(null==as){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型 
		        String filepath="";
		        if(0==type){
		        	filepath= as.getStudentFileUrl();
		        }else if(1==type){
		        	filepath= as.getTeacherFileUrl();
		        }else if(2==type){
		        	filepath= as.getEmployerFileUrl();
		        }
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));   
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		            FileInputStream inputStream = new FileInputStream(file); 
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				      
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						log.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}	
	}
	  
		
		
		@RequestMapping(value="/downloadFileQuestionnaire1" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFileQuestionnaire1(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid){
			try {
				AuthQuestionnaire as = authQuestionnaireService.queryAuthQuestionnaireInfoBypid(pid);
				if(null==as){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= as.getTeacherFileUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));   
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		            FileInputStream inputStream = new FileInputStream(file); 
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				      
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						log.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		
		@RequestMapping(value="/downloadFileQuestionnaire2" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFileQuestionnaire2(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid){
			try {
				AuthQuestionnaire as = authQuestionnaireService.queryAuthQuestionnaireInfoBypid(pid);
				if(null==as){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= as.getEmployerFileUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));   
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		            FileInputStream inputStream = new FileInputStream(file); 
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				      
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						log.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}	
	}
		/**
		 * 保存问卷调查
		 * @param request
		 * @param map
		 * @return
		 * @throws SQLException
		 */
		@RequestMapping(value = "/saveAuthQueDownloadInfo" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
		@ResponseBody
		public ResponseEntity<String> saveAuthQueDownloadInfo(HttpServletRequest request,@RequestBody Map<String,String> map) throws SQLException{
		
			try{
				String pid = map.get("pid");
				AuthQuestionnaire as = authQuestionnaireService.queryAuthQuestionnaireInfoBypid(pid);
				String studentFileUrl = map.get("studentFileName");		
				String teacherFileUrl = map.get("teacherFileName");		
				String employerFileUrl = map.get("employerFileName");
				String overallSatisfaction = map.get("overallSatisfaction");
				String studentFileName=studentFileUrl.substring(studentFileUrl.lastIndexOf("/")+1, studentFileUrl.length());
				String teacherFileName=teacherFileUrl.substring(teacherFileUrl.lastIndexOf("/")+1, teacherFileUrl.length());
				String employerFileName=employerFileUrl.substring(employerFileUrl.lastIndexOf("/")+1, employerFileUrl.length());
				as.setStudentFileName(studentFileName);	
				as.setStudentFileUrl(studentFileUrl);
				as.setTeacherFileName(teacherFileName);	
				as.setTeacherFileUrl(teacherFileUrl);
				as.setEmployerFileName(employerFileName);		
				as.setEmployerFileUrl(employerFileUrl);
				as.setOverallSatisfaction(overallSatisfaction);
				authQuestionnaireService.updateAuthSchoolInfo(as);
				return toResponse(as, ReturnCode.SUCCESS, "保存学生满意度成功");
			}catch(Exception e){
				log.info("保存学生满意度失败", e);
				return toResponse(null,ReturnCode.FAIL,"保存学生满意度失败");
			}
		}
		
		/**
		 * 现场考察--查询问卷调查
		 */
		@RequestMapping(value="/queryQuestionnaireByObservation" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public ResponseEntity<String> queryQuestionnaireByObservation(HttpServletRequest request,HttpServletResponse response){
			String expertId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			if(null == expertId){
				return toResponse(null,ReturnCode.NOLOGIN,"未登录");
			} 
			
			try {
				AuthSchool as = authExportGroupService.querySchoolIdByExpertId(expertId);
				String schoolid = as.getPid();
				AuthSchoolQuestionnaire sq = authQuestionnaireService.queryAuthSchoolQuestionnaireBySchoolId(schoolid);
				return toResponse(sq, ReturnCode.SUCCESS, "查询成功!");
			} catch (SQLException e) {
				e.printStackTrace();
				return toResponse(null, ReturnCode.FAIL, "查询失败!");
			}
			
		}
		
		/**
		 * 现场考察--下载问卷调查
		 * @param request
		 * @param response
		 * @param pid
		 */
		@RequestMapping(value="/downloadFileQuestionnaire3" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.GET)
		@ResponseBody
		public void downloadFileQuestionnaire3(HttpServletRequest request,HttpServletResponse response ,@RequestParam String pid){
			try {
				AuthQuestionnaire as = authQuestionnaireService.queryAuthQuestionnaireInfoBypid(pid);
				if(null==as){
					return ;
				}
				//获取网站部署路径(通过ServletContext对象)，用于确定下载文件位置，从而实现下载  
		        String path = appconfig.getFilePath();  
		        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型  
		        String filepath= as.getTeacherFileUrl();
		        String filename=filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
		        filename = java.net.URLEncoder.encode(filename, "UTF-8");
		        response.setHeader("Content-Type","application/msexcel");
		        response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename));   
		        response.setContentType("application/vnd.ms-excel;charset=utf-8");
		        ServletOutputStream out;  
		        //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)  
		        File file = new File(path +filepath);  
		            FileInputStream inputStream = new FileInputStream(file); 
		            //3.通过response获取ServletOutputStream对象(out)  
		            out = response.getOutputStream();  
		            try {
				         byte[] buffer = new byte[1024];  
				      
				         int count = 0;
				         while ((count = inputStream.read(buffer)) > 0) {
				        	 out.write(buffer, 0, count);
				         }
					} catch (Exception e) {
						log.info("下载文件异常", e);
					}finally{
						inputStream.close();  
			            out.close();  
			            out.flush(); 
					}
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
}
	